<?php

namespace app\common\repositories\system\upload;

use think\facade\Db;
use app\common\services\CacheService;
use app\common\repositories\BaseRepository;
use app\common\dao\system\upload\SystemUploadConfigDao;
use app\common\repositories\property\users\PropertyUsersLogRepository;

class SystemUploadConfigRepository extends BaseRepository
{
    // 存储类型
    const STORAGE_TYPE = [
        'local' => '本地',
        'aliyun' => '阿里云OSS',
        'qiniu' => '七牛云存储',
        'qcloud' => '腾讯云COS'
    ];

    public function __construct(SystemUploadConfigDao $dao)
    {
        $this->dao = $dao;
    }

    public function addInfo(array $data, int $propertyId = 1, int $userId = 0)
    {
        return Db::transaction(function () use ($data, $propertyId, $userId) {
            $data['property_id'] = $propertyId;
            $info = $this->create($data);
            return $info;
        });
    }

    public function editInfo($info, array $data, int $userId = 0)
    {
        return Db::transaction(function () use ($data, $info, $userId) {
            $res = $this->update($info['id'], $data);

            /** @var PropertyUsersLogRepository $repository */
            $repository = app()->make(PropertyUsersLogRepository::class);
            $repository->addInfo($info['property_id'], $userId, 'PROPERTY.UPLOAD.CONFIG.EDIT', $data);
            return $res;
        });
    }

    /**
     * 获取上传配置
     * @param int $propertyId
     * @return mixed
     *
     * @author Amos
     * 2024-01-20 20:28
     */
    public function getConfig(int $propertyId)
    {
        return CacheService::create($propertyId)->remember('upload_config_' . $propertyId, function () use ($propertyId) {
            $res = $this->dao->getSearch([])
                ->where('property_id', $propertyId)
                ->find();
            if ($res) {
                return $res->toArray();
            }
            return $res;
        }, 86400);
    }

}